
#include <FreeTDS/sybfront.h>
#include <FreeTDS/sybdb.h>
#include <assert.h>
#include "wm_MSSqlRow.h"
#include "wormnet/wm_string.h"

namespace worm
{

wmMSSqlRow::wmMSSqlRow(const uint32& dwFieldCount, void* p)
{
    assert(NULL != p);
    if (0 == dwFieldCount)
    {
        assert(0);
        return;
    }

    DBPROCESS* pDb = (DBPROCESS*)p;
    DBINT nRetCode = 0;

    m_pFields = new CDbField[dwFieldCount];

    uint32 dwFieldSize = 0;
    int32 nFieldNo = 0;
    uint32 i = 0;
    int32 nFieldType = 0;
    int32* pFieldStatus = new int32[dwFieldCount];

    for (; i!=dwFieldCount; ++i)
    {
        nFieldNo = i + 1;
        nFieldType = dbcoltype(pDb, nFieldNo);
        dwFieldSize = dbcollen(pDb, nFieldNo);
        if (SYBCHAR != nFieldType)
        {
            dwFieldSize = dbwillconvert(nFieldType, SYBCHAR);;
        }
        ++dwFieldSize;
        m_pFields[i].m_szValue = new char[dwFieldSize];
        if (dbnullbind(pDb, nFieldNo, &pFieldStatus[i]) == FAIL)
        {
            delete []pFieldStatus;
            delete []m_pFields;
            m_pFields = NULL;
            return;
        }
        if (dbbind(pDb, nFieldNo, STRINGBIND, dwFieldSize, (BYTE*)m_pFields[i].m_szValue) == FAIL)
        {
            delete []pFieldStatus;
            delete []m_pFields;
            m_pFields = NULL;
            return;
        }
    }

    for (i=0; i!=dwFieldCount; ++i)
    {
        Trim(m_pFields[i].m_szValue);
    }
}

wmMSSqlRow::~wmMSSqlRow()
{
    if (NULL != m_pFields)
    {
        delete []m_pFields;
        m_pFields = NULL;
    }
}

void wmMSSqlRow::Trim(char* pStr)
{
    uint32 i = strlen(pStr) - 1;
    for (; i!=0; --i)
    {
        if (0 != pStr[i-1])
        {
            pStr[i] = 0;
            break;
        }
    }
}

}
